package u_api

import (
	"com.codingq92/go-chat/app/models"
	"com.codingq92/go-chat/global"
	"com.codingq92/go-chat/utils"
	"errors"
	"strconv"
)

type UserRequest struct {
	models.ID
	Username   string `json:"username"`
	Password   string `json:"password"`
	Headshot   string `json:"headshot"`
	Email      string `json:"email"`
	Phone      string `json:"phone"`
	Province   string `json:"province"`
	City       string `json:"city"`
	Area       string `json:"area"`
	ClientId   string `json:"client_id"`
	ClientPort string `json:"client_port"`
}

// Login 登录
func Login(param UserRequest) (err error, user *models.User) {
	err = global.DB.Where("username=?", param.Username).
		Or("phone=?", param.Username).
		Or("email=?", param.Username).
		First(&user).Error
	if err != nil || !utils.BcryptMakeCheck([]byte(param.Password), user.Password) {
		err = errors.New("用户不存在或密码错误")
	}
	return
}

// Register 注册
func Register(param UserRequest) (err error) {
	var result = global.DB.Where("phone = ?", param.Phone).
		Or("username = ?", param.Username).Or("email = ?", param.Email).
		Select("id").First(&models.User{})
	if result.RowsAffected != 0 {
		err = errors.New("用户已经存在")
		return
	}
	newUser := &models.User{
		Username:   param.Username,
		Password:   utils.BcryptMake([]byte(param.Password)),
		Headshot:   param.Headshot,
		Email:      param.Email,
		Phone:      param.Phone,
		Province:   param.Province,
		City:       param.City,
		Area:       param.Area,
		ClientId:   param.ClientId,
		ClientPort: param.ClientPort,
	}
	err = global.DB.Save(newUser).Error
	return
}

// GetUserInfo 获取用户信息
func GetUserInfo(id string) (err error, user models.User) {
	intId, err := strconv.Atoi(id)
	err = global.DB.First(&user, intId).Error
	if err != nil {
		err = errors.New("用户不存在")
	}
	return
}
